<template>
  <div class="question-page">
   <div v-if="loading" class="loading">
     <p>加载中...</p>
   </div>
   <div v-else-if="currentQuestion" class="question-container">
     <p class="question-title">题目: {{ currentQuestion.questionText }}</p>
     <div v-if="!showCorrectAnswer" class="input-container">
       <label for="user-answer">请输入您的答案:</label>
       <input type="text" id="user-answer" v-model="userAnswer" class="user-answer-input" />
       <button @click="submitAnswer" class="submit-button">提交本题</button>
     </div>
     <div v-else class="answer-container">
       <p>您的答案: {{ userAnswer }}</p>
       <p>正确答案: {{ currentQuestion.answer }}</p>
       <button @click="resetAnswer" class="reset-button">重置答案</button>
     </div>
     <button @click="nextQuestion" class="next-button">下一题</button>
   </div>
   <div v-else class="no-question">
     <p>没有找到题目</p>
   </div>
 </div>
</template>

<script setup name="Question">
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion,listQuestionById } from "@/api/manage/title_detail";
// import {listQuestionbank} from "@/api/manage/title";
const { proxy } = getCurrentInstance();
const { question_type, question_difficulty } = proxy.useDict('question_type', 'question_difficulty');
import { useRoute } from 'vue-router';
// -------------------------------------------------------
import { ref } from 'vue';



const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const userAnswer = ref('');
const showCorrectAnswer = ref(false);

const data = reactive({
 form: {},
 queryParams: {
   pageNum: 1,
   pageSize: 10,
   questionText: null,
   answer: null,
   difficultyLevel: null,
   questionType: null,
   questionBankId: null,
   userId: null,
   topic: null
 },
 rules: {
   questionText: [
     { required: true, message: "题目的文本内容不能为空", trigger: "blur" }
   ],
   answer: [
     { required: true, message: "题目的正确答案不能为空", trigger: "blur" }
   ],
   difficultyLevel: [
     { required: true, message: "题目的难度级别不能为空", trigger: "change" }
   ],
   questionType: [
     { required: true, message: "题目的类型,1选择题2判断题3填空题4简答题不能为空", trigger: "change" }
   ],
   questionBankId: [
     { required: true, message: "题目所属题库不能为空", trigger: "change" }
   ],
   userId: [
     { required: true, message: "出题人不能为空", trigger: "change" }
   ],
   topic: [
     { required: true, message: "题目不能为空", trigger: "blur" }
   ]
 }
});

const { queryParams, form, rules } = toRefs(data);


const questions = ref([]);
onMounted(async() => {
 const route = useRoute();
 const id = route.params.id;
 console.log(id);
 //根据题库id获取题目列表
 await getList(id);
 // console.log(questions);
 //初始化第一题
 await initializeQuestion();
 
})

const getList = async (id) => {
 loading.value = true;
 return listQuestionById(id).then(response => {
   questions.value = response.data;
   loading.value = false;
   return questions.value; // 返回题目列表，确保 await 等待完成
 }).catch(error => {
   console.error('Failed to fetch questions:', error);
   loading.value = false;
 });
};

var currentQuestion = ref(null);

// 初始化第一题
const initializeQuestion = async () => {
 console.log(questions.value);
 if (questions.value && questions.value.length > 0) {
   const firstQuestion = questions.value[0];
   console.log(firstQuestion);
   currentQuestion.value = { ...firstQuestion };
   console.log(currentQuestion.value);
 } else {
   currentQuestion.value = null;
 }
};

// 提交答案
const submitAnswer = () => {
 showCorrectAnswer.value = true;
};

// 重置答案
const resetAnswer = () => {
 userAnswer.value = '';
 showCorrectAnswer.value = false;
};

// 导航到下一题
const nextQuestion = () => {
 const currentIndex = questions.value.findIndex(q => q.id === currentQuestion.value.id);
 if (currentIndex !== -1 && currentIndex < questions.value.length - 1) {
   currentQuestion.value = { ...questions.value[currentIndex + 1] };
   resetAnswer(); // 重置答案和显示状态
 } else {
   alert('已经是最后一题了');
 }
};


</script>
<style scoped>.question-page {
 max-width: 800px;
 margin: 0 auto;
 padding: 20px;
 background-color: #f9f9f9;
 border-radius: 10px;
 box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.loading {
 text-align: center;
 font-size: 1.2em;
 color: #666;
}

.question-container {
 margin-top: 20px;
}

.question-title {
 font-size: 1.5em;
 margin-bottom: 10px;
 color: #333;
}

.input-container {
 margin-bottom: 20px;
}

.user-answer-input {
 width: 100%;
 padding: 10px;
 margin-top: 5px;
 border: 1px solid #ccc;
 border-radius: 5px;
 font-size: 1em;
}

.submit-button,
.reset-button,
.next-button {
 padding: 10px 20px;
 margin-top: 10px;
 border: none;
 border-radius: 5px;
 font-size: 1em;
 cursor: pointer;
 transition: background-color 0.3s;
}

.submit-button {
 background-color: #28a745;
 color: white;
}

.submit-button:hover {
 background-color: #218838;
}

.reset-button {
 background-color: #dc3545;
 color: white;
}

.reset-button:hover {
 background-color: #c82333;
}

.next-button {
 background-color: #007bff;
 color: white;
}

.next-button:hover {
 background-color: #0056b3;
}

.answer-container {
 margin-top: 20px;
}

.no-question {
 text-align: center;
 font-size: 1.2em;
 color: #666;
}
</style>




<!-- <template>
  <div class="question-page">
    <div v-if="currentQuestion" class="question-container">
      <h2>{{ currentQuestion.question }}</h2>
      <textarea 
        v-model="currentQuestion.answer" 
        placeholder="请输入你的答案" 
        class="answer-textarea" 
      />
      <button @click="resetAnswer">重置</button>
      <button @click="nextQuestion">下一题</button>
      <button @click="submitAnswer">提交</button>
    </div>
    <div v-else>
      <p>没有更多的题目了。</p>
    </div>
  </div>
</template>

<script setup name="Question">
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion,listQuestionById } from "@/api/manage/title_detail";
import {listQuestionbank} from "@/api/manage/title";
const { proxy } = getCurrentInstance();
const { question_type, question_difficulty } = proxy.useDict('question_type', 'question_difficulty');
import { useRoute } from 'vue-router';
// -------------------------------------------------------
import { ref } from 'vue';

// 假设这是从服务器获取的题目列表
const questions = questionList;

const currentQuestion = ref(null);

// 初始化第一题
const initializeQuestion = () => {
  const firstQuestion = questions.value[0];
  currentQuestion.value = { ...firstQuestion };
};

// 重置答案
const resetAnswer = () => {
  currentQuestion.value.answer = '';
};

// 下一题
const nextQuestion = () => {
  const currentIndex = questions.value.findIndex(q => q.id === currentQuestion.value.id);
  if (currentIndex < questions.value.length - 1) {
    const nextQuestion = questions.value[currentIndex + 1];
    currentQuestion.value = { ...nextQuestion };
  } else {
    alert('已经是最后一题了！');
  }
};

// 提交答案
const submitAnswer = () => {
  if (currentQuestion.value.answer.trim() === '') {
    alert('请填写答案后再提交！');
    return;
  }
  // 这里可以添加提交答案到服务器的逻辑
  console.log('提交答案：', currentQuestion.value);
  // 自动跳转到下一题
  nextQuestion();
};

// 初始化第一题
initializeQuestion();



//------------------------------------------------------------------
// 获取当前路由信息
const route = useRoute();

// 从路由参数中获取 id
const id = route.params?.id ?? route.query?.id;


const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  questionList : ref([]),
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    questionText: null,
    answer: null,
    difficultyLevel: null,
    questionType: null,
    questionBankId: null,
    userId: null,
    topic: null
  },
  rules: {
    questionText: [
      { required: true, message: "题目的文本内容不能为空", trigger: "blur" }
    ],
    answer: [
      { required: true, message: "题目的正确答案不能为空", trigger: "blur" }
    ],
    difficultyLevel: [
      { required: true, message: "题目的难度级别不能为空", trigger: "change" }
    ],
    questionType: [
      { required: true, message: "题目的类型,1选择题2判断题3填空题4简答题不能为空", trigger: "change" }
    ],
    questionBankId: [
      { required: true, message: "题目所属题库不能为空", trigger: "change" }
    ],
    userId: [
      { required: true, message: "出题人不能为空", trigger: "change" }
    ],
    topic: [
      { required: true, message: "题目不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

// /** 查询题目展示列表 */
function getList() {
  loading.value = true;
  listQuestion(queryParams.value).then(response => {
    questionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    questionText: null,
    answer: null,
    difficultyLevel: null,
    questionType: null,
    questionBankId: null,
    userId: null,
    creatTime: null,
    updataTime: null,
    isDelete: null,
    topic: null
  };
  proxy.resetForm("questionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// // 多选框选中数据
// function handleSelectionChange(selection) {
//   ids.value = selection.map(item => item.id);
//   single.value = selection.length != 1;
//   multiple.value = !selection.length;
// }

// /** 新增按钮操作 */
// function handleAdd() {
//   reset();
//   open.value = true;
//   title.value = "添加题目展示";
// }

// /** 修改按钮操作 */
// function handleUpdate(row) {
//   reset();
//   const _id = row.id || ids.value
//   getQuestion(_id).then(response => {
//     form.value = response.data;
//     open.value = true;
//     title.value = "修改题目展示";
//   });
// }

/**查看题目详情 */
const openQuestion = ref(false);
const dateById  = ref([]);
function handleselect(row){
  reset();
  const _id = row.id || ids.value
  listQuestionById(_id).then(response => {
    dateById.value = response.data;
    openQuestion.value = true;
    title.value = "题目详情";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["questionRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

onMounted(() => {
  getqustList(id);
}),


function getqustList(id){
  listQuestionById(id).then(response => {
    questionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// getQuestionbankList();
// getList();
getqustList(id);
</script>

 -->
